// 写一个给请求队列的一个类
class RequestQueue {
  /**
   * 最大请求数
   */
  private max: number;
  /**
   * 当前请求数
   */
  private currentConcurrent: number;
  private queue: any[];
  constructor(max: number) {
    this.max = max;
    this.currentConcurrent = 0;
    this.queue = [];
  }
  /**
   * 添加请求
   */
  add(request: any) {
    return new Promise((resolve, reject) => {
      this.queue.push({ request, resolve, reject });
      this.processQueue();
    });
  }

  /**
   * 修改队列之后，处理队列数据
   */
  processQueue() {
    // 队列中有数据，且并且当前并发数小于最大并发数
    if (this.queue.length > 0 && this.currentConcurrent < this.max) {
      // 取出最早一个请求
      const { request, resolve, reject } = this.queue.shift();
      // 更新当前并发数
      this.currentConcurrent++;
      request()
        .then(resolve)
        .catch(reject)
        .finally(() => {
          this.currentConcurrent--;
          this.processQueue();
        });
    }
  }
}

function fetchData(url: string) {
  return fetch(url).then(res => res.json());
}
const requestQueue = new RequestQueue(5);

const urls = [
  "https://jsonplaceholder.typicode.com/posts/1",
  "https://jsonplaceholder.typicode.com/posts/2",
];
// 获取包含请求结果的函数数组
const reqs = urls.map(url => () => fetchData(url));
// 添加请求到请求队列
const reqsSolved = reqs.map(req => requestQueue.add(req));
function Sleep() {
  return new Promise(resolve => setTimeout(resolve, 1000));
}

(async function () {
  const res1 = await reqsSolved[0];
  console.log('RESULT', res1);
  await Sleep();
  const res2 = await reqsSolved[1];
  console.log('RESULT', res2);
})();
